import { Injectable, signal } from '@angular/core';
import { Observable, tap } from 'rxjs';
import { LouYuan } from '../models/louyuan.model';
import { MyBaseService } from './mybaseservice.service';

@Injectable({
  providedIn: 'root'
})
export class LouYuanService extends MyBaseService {
  private _allLouYuan = signal<LouYuan[]>([]);
  get allLouYuan() {
    return this._allLouYuan.asReadonly();
  }

  constructor() { super(); }

  addLouYuan(data: LouYuan): Observable<LouYuan> {
    return this.httpClient.post<LouYuan>(this.backendURL + "/louyuan", data).pipe(
      tap({
        next: data => this._allLouYuan.update(item => [...item, data])
      })
    )
  }

  getAllLouYuan(): Observable<LouYuan[]> {
    return this.httpClient.get<LouYuan[]>(this.backendURL + "/louyuan/all").pipe(
      tap({
        next: data => this._allLouYuan.set(data)
      })
    );
  }

  getLouYuanByID(id: string): Observable<LouYuan> {
    return this.httpClient.get<LouYuan>(this.backendURL + "/louyuan/" + id);
  }

  updateLouYuan(data: LouYuan): Observable<LouYuan> {
    return this.httpClient.put<LouYuan>(this.backendURL + "/louyuan", data).pipe(
      tap({
        next: (data) => {
          this._allLouYuan.update((previewArray) => {
            let index = previewArray.findIndex(item => item.louYuanID === data.louYuanID);
            if (index !== -1) {
              previewArray[index] = data;
            }
            return previewArray;
          });
        }
      })
    )
  }

  deleteLouYuan(id: string): Observable<void> {
    return this.httpClient.delete<void>(this.backendURL + "/louyuan/" + id).pipe(
      tap({
        next: data => this._allLouYuan.update((previewArray) => {
          return previewArray.filter(item => item.louYuanID !== id);
        })
      })
    )
  }
}
